<template>
  <view class="countdown-box">
    <view class="countDown">
      <text>{{ hh }}</text>
      <text>:</text>
      <text>{{ mm }}</text>
      <text>:</text>
      <text>{{ ss }}</text>
    </view>
  </view>
</template>

<script>
import { diyMixin } from "../mixins/diy";

export default {
  props: {
    propsData: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  mixins: [diyMixin], //混入文件
  data() {
    return {
      hh: "00",
      mm: "00",
      ss: "00",
    };
  },
  methods: {
    countDown() {
      let startTime = new Date(this.propsData.startTime).getTime();
      let endTime = new Date(this.propsData.endTime).getTime();
      switch (uni.getSystemInfoSync().platform) {
        case "ios":
          startTime = new Date(
            this.propsData.startTime.replace(/-/g, "/")
          ).getTime();
          endTime = new Date(
            this.propsData.endTime.replace(/-/g, "/")
          ).getTime();
          break;
      }
      let now = new Date().getTime();
      if (now < startTime) {
        this.hh = "00";
        this.ss = "00";
        this.mm = "00";
      }
      if (startTime < now && now < endTime) {
        let timer = setInterval(() => {
          var EndTime = endTime / 1000; //结束时间
          var NowTime = new Date(); //当前时间
          if (EndTime <= NowTime.getTime() / 1000) {
            clearInterval(timer);
            this.countDown();
          } else {
            //后台给我的是10位 精确到秒的  所有下面我就除以了1000，不要小数点后面的
            var t = EndTime - (NowTime.getTime() / 1000).toFixed(0);
            //如果后台给的是毫秒 上面不用除以1000  下面的计算时间也都要除以1000 这里我去掉1000了
            var h = Math.floor(t / 60 / 60); //时 var h=Math.floor(t/1000/60/60%24)
            var m = Math.floor((t / 60) % 60); //分 var m=Math.floor(t/1000/60%60)
            var s = Math.floor(t % 60); //秒 var s=Math.floor(t/1000%60)
            if (parseInt(h) < 10) {
              h = "0" + h;
            }
            if (parseInt(m) < 10) {
              m = "0" + m;
            }
            if (parseInt(s) < 10) {
              s = "0" + s;
            }
            this.hh = h;
            this.mm = m;
            this.ss = s;
          }
        }, 1000);
      }
      if (now >= endTime) {
        this.hh = "00";
        this.ss = "00";
        this.mm = "00";
      }
    },
  },
  created() {
    if (this.propsData.startTime != "" && this.propsData.endTime != "") {
      this.countDown();
    }
  },
};
</script>

<style scoped lang="scss">
.countDown {
  margin-left: 16rpx;
  display: flex;
  align-items: center;
  font-size: 20rpx;
  font-weight: 600;
  text:nth-child(2n + 1) {
    width: 30rpx;
    height: 30rpx;
    background-color: #fc402f;
    border-radius: 6rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
  }
  text:nth-child(2n) {
    color: #fc402f;
    margin: 0 6rpx;
  }
}
</style>
